<template>
  <div class="dashboard-wrapper">
    <!-- 数据卡片区域 -->
    <el-row class="data-cards">
      <el-col :span="6">
        <!-- 数据卡片1：受保人总数 -->
        <el-card class="data-card hover-effect">
          <div class="card-content">
            <div class="card-icon bg-blue-100">
              <i class="el-icon-user-filled text-blue-600"></i>
            </div>
            <div class="card-title">受保人总数</div>
            <div class="card-value">{{ MBRCount.count }}</div>
            <div class="card-change">
              <span class="change-text text-green">‎</span>
              <span class="change-desc">‎</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <!-- 数据卡片2：报销单总数 -->
        <el-card class="data-card hover-effect">
          <div class="card-content">
            <div class="card-icon bg-purple-100">
              <i class="el-icon-document text-purple-600"></i>
            </div>
            <div class="card-title">报销单总数</div>
            <div class="card-value">{{ rbCount.thisMonthCount }}</div>
            <div class="card-change">
              <span class="change-text text-green">
                {{ rbCount.thisMonthCount > rbCount.lastMonthCount ? "+" : ""
                }}{{ rbCount.thisMonthCount - rbCount.lastMonthCount }}条
              </span>
              <span class="change-desc">较上月</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <!-- 数据卡片3：本月使用人次 -->
        <el-card class="data-card hover-effect">
          <div class="card-content">
            <div class="card-icon bg-orange-100">
              <i class="el-icon-calendar text-orange-600"></i>
            </div>
            <div class="card-title">本月使用人次</div>
            <div class="card-value">{{ userLoginCount.thisMonthCount }}</div>
            <div class="card-change">
              <span :class="['change-text', getChangeColor(userLoginCount)]">
                {{
                  userLoginCount.thisMonthCount > userLoginCount.lastMonthCount
                    ? "+"
                    : ""
                }}{{
                  userLoginCount.thisMonthCount - userLoginCount.lastMonthCount
                }}人次
              </span>
              <span class="change-desc">较上月</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <!-- 数据卡片4：报销单诈骗数量 -->
        <el-card class="data-card hover-effect">
          <div class="card-content">
            <div class="card-icon bg-red-100">
              <i class="el-icon-warning text-red-600"></i>
            </div>
            <div class="card-title">报销单诈骗数量</div>
            <div class="card-value">{{ rbFraudCount.fraudCount }}</div>
            <div class="card-change">
              <span class="change-text text-red">
                {{
                  (((rbFraudCount.fraudCount || 0) /
                    (rbCount.thisMonthCount || 0)) *
                  100).toFixed(2)
                }}%
              </span>
              <span class="change-desc">诈骗占比</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row class="charts-section">
      <el-col :span="12">
        <!-- 图表1：近五次上传报销单诈骗占比 -->
        <el-card class="chart-card">
          <div class="chart-header">
            <div class="chart-title">近五次上传报销单诈骗占比</div>
          </div>
          <div class="chart-container" ref="recentUploadFraudChartRef">
            <!-- 诈骗占比图表将通过ECharts渲染 -->
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <!-- 图表2：报销类型分布 -->
        <el-card class="chart-card">
          <div class="chart-header">
            <div class="chart-title">报销单诈骗占比</div>
          </div>
          <div class="chart-container" ref="fraudChartRef">
            <!-- 诈骗占比图表将通过ECharts渲染 -->
          </div>
        </el-card>
      </el-col>

      

    </el-row>
  </div>
</template>

<script>
import { getCurrentInstance, ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";

export default {
  name: "Dashboard",
  setup() {
    // 获取composition api的全局对象
    const { proxy } = getCurrentInstance();
    // 受保人数量
    const MBRCount = ref(0);
    // 报销单数量
    const rbCount = ref({
      thisMonthCount: 0,
      lastMonthCount: 0,
    });
    // 本月和上月使用人次
    const userLoginCount = ref({
      thisMonthCount: 0,
      lastMonthCount: 0,
    });
    // 报销单诈骗数量
    const rbFraudCount = ref({ fraudCount: 0 });
    // 最近五次上传的报销单的诈骗与非诈骗数量
    const recentUploadRbFraudCount = ref({
      fraudCount: 0,
      normalCount: 0,
    });

    // 诈骗占比图表的ref
    const fraudChartRef = ref(null);
    // 存储图表实例
    let fraudChart = null;

    // 最近上传报销单的诈骗占比图表的ref
    const recentUploadFraudChartRef = ref(null);
    // 存储图表实例
    let recentUploadFraudChart = null;

    onMounted(() => {
      getMBRCount();
      getRbCount();
      getUserLoginCount();
      getRbFraudCount();
      getRecentUploadRbFraudCount();
      initFraudChart();
      initRecentUploadFraudChart();

      // 监听数据变化，更新图表
      watch(
        [rbCount, rbFraudCount, recentUploadRbFraudCount],
        updateFraudChart
      );
    });

    // 窗口大小变化时，重新调整图表大小
    window.addEventListener("resize", () => {
      if (fraudChart) {
        fraudChart.resize();
      }
    });

    // 计算变化的颜色类
    const getChangeColor = (data) => {
      const current = data.thisMonthCount;
      const previous = data.lastMonthCount;

      if (current >= previous) {
        return "text-green";
      } else if (current < previous) {
        return "text-red";
      }
    };

    // 获取MBR总数
    const getMBRCount = async () => {
      try {
        MBRCount.value = await proxy.$api.getMbrCount();
      } catch (error) {}
    };

    // 获取报销单总数
    const getRbCount = async () => {
      try {
        // const { thisMonthCount, lastMonthCount } =
        //   await proxy.$api.getRbCount();
        // rbCount.value.thisMonthCount = thisMonthCount;
        // rbCount.value.lastMonthCount = lastMonthCount;
        rbCount.value = await proxy.$api.getRbCount();
      } catch (error) {
        ElMessage.error("获取报销单总数失败");
      }
    };

    // 获取登录记录
    const getUserLoginCount = async () => {
      try {
        userLoginCount.value = await proxy.$api.getUserLoginCount();
      } catch (error) {
        ElMessage.error("获取登录记录失败");
      }
    };

    // 获取报销单诈骗数量
    const getRbFraudCount = async () => {
      try {
        rbFraudCount.value = await proxy.$api.getRbFraudCount();
      } catch (error) {
        ElMessage.error("获取报销单诈骗数量失败");
      }
    };

    // 初始化诈骗占比图表
    const initFraudChart = () => {
      if (!fraudChartRef.value) return;

      // 初始化图表
      fraudChart = echarts.init(fraudChartRef.value);

      // 设置图表选项
      const option = {
        tooltip: {
          trigger: "item",
          // {a}表示系列名称，{b}表示数据项名称，{c}表示数据项的值，{d}表示数据项的百分比。
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          textStyle: {
            color: "#333",
          },
          borderColor: "#eee",
          borderWidth: 1,
          padding: 10,
          extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          orient: "vertical",
          right: "10%",
          top: "center",
          itemWidth: 12,
          itemHeight: 12,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
        },
        series: [
          {
            name: "报销单类型",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["35%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "outside",
              formatter: "{b}: {d}%",
              fontStyle: "normal",
              fontWeight: "normal",
              fontFamily: "sans-serif",
              fontSize: 13,
              color: "#606266",
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20,
              lineStyle: {
                color: "#e6e6e6",
              },
            },
            data: [
              {
                value: 0,
                name: "诈骗",
                itemStyle: {
                  color: "#f56c6c",
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.3)",
                  },
                },
              },
              {
                value: 0,
                name: "正常",
                itemStyle: {
                  color: "#67c23a",
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.3)",
                  },
                },
              },
            ],
          },
        ],
        color: ["#f56c6c", "#67c23a"],
        animationDuration: 1000,
        animationEasing: "cubicOut",
      };

      // 设置图表选项
      fraudChart.setOption(option);

      // 初始更新图表数据
      updateFraudChart();
    };

    // 更新诈骗占比图表数据
    const updateFraudChart = () => {
      if (!fraudChart || !recentUploadFraudChart) return;

      // 确保数据已加载
      const fraudCount = rbFraudCount.value.fraudCount || 0;
      const totalCount = rbCount.value.thisMonthCount || 0;
      const normalCount = Math.max(0, totalCount - fraudCount); // 确保不会出现负数

      const recentFraudCount = recentUploadRbFraudCount.value.fraudCount || 0;
      const recentNormalCount = recentUploadRbFraudCount.value.normalCount || 0;

      // 更新图表数据
      fraudChart.setOption({
        series: [
          {
            data: [
              {
                value: fraudCount,
                name: "诈骗",
                itemStyle: { color: "#f56c6c" },
              },
              {
                value: normalCount,
                name: "正常",
                itemStyle: { color: "#67c23a" },
              },
            ],
          },
        ],
      });

      recentUploadFraudChart.setOption({
        series: [
          {
            data: [
              {
                value: recentFraudCount,
                name: "诈骗",
                itemStyle: { color: "#f56c6c" },
              },
              {
                value: recentNormalCount,
                name: "正常",
                itemStyle: { color: "#67c23a" },
              },
            ],
          },
        ],
      });
    };

    // 获取最近五次上传的报销单的诈骗与非诈骗数量
    const getRecentUploadRbFraudCount = async () => {
      try {
        recentUploadRbFraudCount.value =
          await proxy.$api.getRecentUploadRbFraudCount();
        console.log(
          "最近五次上传的报销单的诈骗与非诈骗数量=>",
          recentUploadRbFraudCount.value
        );
      } catch (error) {
        ElMessage.error("获取最近五次上传的报销单的诈骗与非诈骗数量失败");
      }
    };

    // 初始化近五次上传报销单诈骗占比图表
    const initRecentUploadFraudChart = () => {
      if (!recentUploadFraudChartRef.value) return;

      recentUploadFraudChart = echarts.init(recentUploadFraudChartRef.value);

      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: "rgba(255, 255, 255, 0.9)",
          textStyle: {
            color: "#333",
          },
          borderColor: "#eee",
          borderWidth: 1,
          padding: 10,
          extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);",
        },
        legend: {
          orient: "vertical",
          right: "10%",
          top: "center",
          itemWidth: 12,
          itemHeight: 12,
          textStyle: {
            color: "#606266",
            fontSize: 13,
          },
        },
        series: [
          {
            name: "近五次上传报销单类型",
            type: "pie",
            radius: ["40%", "70%"],
            center: ["35%", "50%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "outside",
              formatter: "{b}: {d}%",
              fontStyle: "normal",
              fontWeight: "normal",
              fontFamily: "sans-serif",
              fontSize: 13,
              color: "#606266",
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20,
              lineStyle: {
                color: "#e6e6e6",
              },
            },
            data: [
              {
                value: 0,
                name: "诈骗",
                itemStyle: {
                  color: "#f56c6c",
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.3)",
                  },
                },
              },
              {
                value: 0,
                name: "正常",
                itemStyle: {
                  color: "#67c23a",
                },
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: "rgba(0, 0, 0, 0.3)",
                  },
                },
              },
            ],
          },
        ],
        color: ["#f56c6c", "#67c23a"],
        animationDuration: 1000,
        animationEasing: "cubicOut",
      };

      recentUploadFraudChart.setOption(option);
    };

    return {
      rbCount,
      MBRCount,
      userLoginCount,
      rbFraudCount,
      recentUploadRbFraudCount,
      getChangeColor,
      getMBRCount,
      getRbCount,
      getUserLoginCount,
      getRbFraudCount,
      getRecentUploadRbFraudCount,
      initFraudChart,
      updateFraudChart,
      initRecentUploadFraudChart,
      fraudChartRef,
      recentUploadFraudChartRef,
    };
  },
};
</script>

<style lang="scss">
.dashboard-wrapper {
  padding: 20px;
}

.data-cards {
  margin-bottom: 20px;

  .data-card {
    text-align: center;
    padding: 20px;
    border-radius: 12px;
    transition: all 0.3s ease;

    .card-icon {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 60px;
      border-radius: 50%;
      margin-bottom: 15px;

      i {
        font-size: 24px;
      }
    }

    .card-title {
      font-size: 16px;
      font-weight: 500;
      color: #606266;
      margin-bottom: 10px;
    }

    .card-value {
      font-size: 32px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 15px;
    }

    .card-change {
      display: flex;
      justify-content: center;
      align-items: center;

      .change-text {
        font-weight: 500;
        margin-right: 5px;
      }

      .change-desc {
        font-size: 12px;
        color: #909399;
      }

      .text-green {
        color: #67c23a;
      }

      .text-red {
        color: #f56c6c;
      }
    }
  }

  .hover-effect:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
  }
}

.charts-section {
  .chart-card {
    border-radius: 12px;
    margin-bottom: 20px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .chart-title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }

    .chart-container {
      height: 300px;
    }
  }
}
</style>
